<?php
declare(strict_types=1);

namespace app\index\controller;

use app\index\BootStarup;
use lib\pay\helpers\PaySign;
use lib\pay\MemberPay;
use lib\pay\Pay;
use lib\pay\XinPay;
use Swoole\Http\Request;
use Swoole\Http\Response;
use sys\Log;

class Callback {
    /**
     * 嘉联支付回调接口
     */
    public function jlnotify(Request $request, Response $response) {

        $check = validate([
            'sid'=>'require|uinteger'
        ], __LINE__ . __FILE__)->check($request->get);
        if(!$check->pass()){
            return ['retCode'=>'false'];
        }

        if((int)$request->get['sid'] !== BootStarup::$sid){
            Log::write('服务器ID错误!' . $request->get['sid'] . '!=' . BootStarup::$sid, 'ERROR');
            return ['retCode'=>'false'];
        }

        $params = json_decode($request->getContent(), true);
        # $ipaddr = $request->header['x-real-ip'] ?? $request->server['remote_addr'];

        if(true == PaySign::verify($params)){
            XinPay::onNotify($params);
            return ['retCode'=>'success'];
        }
        # 验签未通过
        return ['retCode'=>'false'];
    }

    /**
     * 会员支付回调接口
     */
    public function mnotify(Request $request, Response $response) {
        $chekc = validate([
            'sid'=>'require|uinteger'
        ], __LINE__ . __FILE__)->check($request->get);
        if(!$chekc->pass()){ return ['retCode'=>'false'];}

        if((int)$request->get['sid'] !== BootStarup::$sid){
            Log::write('服务器ID错误!' . $request->get['sid'] . '!=' . BootStarup::$sid, 'ERROR');
            return ['retCode'=>'false'];
        }

        $params = json_decode($request->getContent(), true);

        if(true == PaySign::verify($params, Pay::SRC_MEMBER)){
            MemberPay::onNotify($params);
            return ['retCode'=>'success'];
        }
        # 验签未通过
        return ['retCode'=>'false'];
    }


    private function createpkeypair($bits = 512)
    {
        $config = array(
            "digest_alg" => "sha256",
            "private_key_bits" => $bits,
            "private_key_type" => OPENSSL_KEYTYPE_RSA,
        );

        //创建公钥私钥对
        $res = openssl_pkey_new($config);
        //生成私钥
        openssl_pkey_export($res, $privkey, NULL, $config);
        $pubres =openssl_pkey_get_details($res);
        if($pubres){
            $pubkey = $pubres['key'];
        }
        openssl_pkey_free($res);
        
        $pkey = openssl_get_publickey($pubres['key']);
        
        return ['pubkey'=>$pubres['key'], 'privkey'=>$privkey];
    }

    public function cp(Request $request, Response $response){
        $data = $this->createpkeypair(2048);
        $response->header('Content-Type', 'text/html; charset=utf-8');
        return '<p>2048公钥:</p><pre>'. $data['pubkey'] . '</pre><p>私钥:</p><pre>'. $data['privkey']. '</pre>';
    }
}